package cn.omisheep.au.core;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

@Slf4j
public class AuRsa {

    @Data
    @AllArgsConstructor
    public static class AuKeyPair {
        private String publicKey;
        private String privateKey;

        @Override
        public String toString() {
            return "\npublicKey=\n" + publicKey +
                    "\nprivateKey=\n" + privateKey;
        }
    }


    /**
     * 随机生成密钥对
     *
     * @return AuKeyPair密钥对
     * @throws NoSuchAlgorithmException e
     */
    public static AuKeyPair genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map，0表示公钥 1表示私钥
        return new AuKeyPair(publicKeyString, privateKeyString);
    }


    /**
     * RSA公钥加密
     *
     * @param str       明文
     * @param publicKey 公钥
     * @return 加密字符串
     */
    @SneakyThrows
    public static String encrypt(String str, String publicKey) {
        return RSAUtil.encryptString(RSAUtil.getPublicKey(publicKey), str);
    }


    /**
     * RSA私钥解密
     *
     * @param str        秘文
     * @param privateKey 私钥
     * @return 明文
     */
    @SneakyThrows
    public static String decrypt(String str, String privateKey) {
        return RSAUtil.decryptString(RSAUtil.getPrivateKey(privateKey), bugfix(str));
    }


    public static String bugfix(String text) {
        return text.replaceAll(" ", "+");//!!!!!
    }

}